package com.zbl.javaDemo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

public class CompletableFutureDemo {
    public static void main(String[] args) throws Exception {
        // 异步任务
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> "hello", Executors.newFixedThreadPool(10));
        // 异步回调任务，有返回值
        CompletableFuture<String> callBackCf = cf.thenApplyAsync(rs -> rs + " world");
        // 异步回调任务，无返回值
        cf.thenAcceptAsync(rs -> System.out.println(rs + " world"));
        // 纯异步回调任务
        cf.thenRunAsync(() -> System.out.println("Hello world"));
        // 异步回调任务,带异常参数，返回原cf
        CompletableFuture<String> whenCf = cf.whenCompleteAsync((rs, ex) -> System.out.println(rs + " world"));
        // 异步回调任务,带异常参数，有返回值
        CompletableFuture<String> handleCf = cf.handleAsync((rs, ex) -> rs + " world");
        System.in.read();
    }

    private static void extracted() throws InterruptedException, ExecutionException {
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("开始执行任务1");
            return "任务1";
        });
        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("开始执行任务2");
            return "任务2";
        });
        CompletableFuture<Object> completableFuture = CompletableFuture.anyOf(cf1, cf2).whenComplete((ans, ex) -> {
            System.out.println("已完成" + ans);
            if (ex != null) {
                System.out.println("发生异常：" + ex.getMessage());
            }
        });
        System.out.println("获取CF结果：" + completableFuture.get());
    }
}
